package org.xtext.runtime.control;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.xtext.runtime.interpreter.Agent;

public class Executor implements Runnable {
	List<IExecutable> agents = Collections.synchronizedList(new LinkedList<IExecutable>());
	Object lock = new Object();
	boolean shutdown = false;
	
	public void run() {
		
		while (!isShutdown()) {
			synchronized (lock) {
				for (IExecutable a : agents) {
					a.execute();
				}
			}
		}
	}
	
	public synchronized boolean isShutdown() {
		return shutdown;
	}
	
	public synchronized void shutdown(boolean shutdown) {
		this.shutdown = shutdown;
	}
	
	public void addAgent(IExecutable a) {
		synchronized (lock) {
			agents.add(a);
		}
	}

	public void removeAgent(Agent agent) {
		synchronized (lock) {
			agents.remove(agent);
		}
	}

	public void shutdown() {
		agents.clear();
		shutdown(true);
	}

}
